package appserver;
import session.*;

import java.util.PriorityQueue;
import java.util.concurrent.ConcurrentHashMap;

public class Cache extends ConcurrentHashMap<SessionID, Session> {

	private PriorityQueue<Session> order= new PriorityQueue<Session>();
	private final int CacheSize;
	
	Cache(int cacheSize){
		super();
		CacheSize= cacheSize;
		
	}
	
	//overridden put() method, returns the evicted session if overflows cachelimit
	@Override
	public Session put(SessionID sid, Session curSess) {
		Session rVal;
		SessionID rKey;
		Session evicted= null;
		if (this.size()>= CacheSize)
		{
			synchronized (order) {
				rVal= order.poll();
			}
			rKey= rVal.getSessionID();
			if (rKey!= null && this.containsKey(rKey))
			{
				evicted= this.remove(rKey);
			}
		}
		super.put(sid, curSess);
		synchronized (order) {
			order.add(curSess);
		}
		return evicted;
	}

	//only called after a nullcheck
	public boolean hasFreshVersion(SessionID sid, SSMCookie curCook){
		//redundant null check
		if (!this.containsKey(sid))
				return false;
		Session sessCached= this.get(sid);
		int versReq= curCook.getSessionVersion();
		int versCached= sessCached.getSessionVersion();
		return (versReq==versCached);
	}

	
	
	public Session flushStale(SessionID sid)
	{
		if (!this.containsKey(sid))
			return null;
		synchronized (order) {
			order.remove(this.get(sid));
		}
		return this.remove(sid);
	}

}
